package com.huoxingy.print;

import com.aliyun.openservices.ons.api.MessageListener;
import com.aliyun.openservices.ons.api.PropertyKeyConst;
import com.aliyun.openservices.ons.api.bean.ConsumerBean;
import com.aliyun.openservices.ons.api.bean.Subscription;
import com.jayway.jsonpath.Option;
import com.jayway.jsonpath.spi.json.JacksonJsonProvider;
import com.jayway.jsonpath.spi.mapper.JacksonMappingProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * Created by hanxi on 2018/10/9.
 */
@Configuration
public class AppConfig {
    @Autowired
    private OrderMessageListener listener;

    @Value(value = "${ons.consumer.id}")
    private String onsConsumerId;
    @Value(value = "${ons.access-key}")
    private String onsAccessKey;
    @Value(value = "${ons.secret-key}")
    private String onsSecretKey;
    @Value(value = "${ons.consumer.thread-count}")
    private String onsConsumeThreadNums;
    @Value(value = "${ons.topic.order}")
    private String topic;
    @Value(value = "${ons.addr}")
    private String onsAddr;

    @Bean(initMethod = "start", destroyMethod = "shutdown")
    public ConsumerBean onsConsumerBean() {
        ConsumerBean consumer = new ConsumerBean();

        Properties props = new Properties();
        props.setProperty(PropertyKeyConst.ConsumerId, onsConsumerId);
        props.setProperty(PropertyKeyConst.AccessKey, onsAccessKey);
        props.setProperty(PropertyKeyConst.SecretKey, onsSecretKey);
        props.setProperty(PropertyKeyConst.ConsumeThreadNums, onsConsumeThreadNums);
        props.put(PropertyKeyConst.ONSAddr, this.onsAddr);
        consumer.setProperties(props);

        Subscription sub = new Subscription();
        sub.setTopic(topic);

        Map<Subscription, MessageListener> subs = new HashMap<>();
        subs.put(sub, this.listener);

        consumer.setSubscriptionTable(subs);

        return consumer;
    }

    @Bean
    public com.jayway.jsonpath.Configuration jsonConfig() {
        return com.jayway.jsonpath.Configuration.builder()
                .jsonProvider(new JacksonJsonProvider())
                .mappingProvider(new JacksonMappingProvider())
                .options(Option.DEFAULT_PATH_LEAF_TO_NULL).build();
    }
}
